import {asyncRoutes, constantRoutes} from '@/router';
import {defineStore} from 'pinia';
import {store} from '@/store';
import {clone} from 'nices';
import settings from '@/settings.js';


function inWhite(roles) {
  for(let i = 0; i < roles.length; i++) {
    if (settings.whiteRoles.includes(roles[i])) return true;
  }
  return false;
}

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

function filterAsyncRoutes(routes, roles) {
  const asyncRoutes = [];

  routes.forEach(route => {
    const tmpRoute = clone(route);
    if (hasPermission(roles, tmpRoute)) {
      if (tmpRoute.children) {
        tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
      }
      asyncRoutes.push(tmpRoute);
    }
  })

  return asyncRoutes;
}

export const usePermissionStore = defineStore({
  id: 'permission',
  state: () => ({
    routes: [],
    addRoutes: []
  }),
  actions: {
    generateRoutes(roles) {
      return new Promise((resolve) => {
        let accessedRoutes;

        if (inWhite(roles)) accessedRoutes = asyncRoutes || [];
        else accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        
        this.addRoutes = accessedRoutes;
        this.routes = constantRoutes.concat(accessedRoutes);
        resolve(accessedRoutes);
      });
    }
  }
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}